'use strict';
const Controller = require('egg').Controller;
const JWT = require('jsonwebtoken');
const path = require('path');
// const officegen = require('officegen');
// const fs = require('fs');
const fse = require('fs-extra');
const formidable = require('formidable');
const multiparty = require('multiparty');
// const bodyparser = require('koa-bodyparser');
const extractExt = filename =>
  filename.slice(filename.lastIndexOf('.'), filename.length); // 提取后缀名
const UPLOAD_DIR = path.resolve(__dirname, '..', 'target'); // 大文件存储目录
class HomeController extends Controller {
  async index() {
    const result = await this.app.mysql.get('blog_content', {});
    this.ctx.body = `媛媛${JSON.stringify(result)}`;
  }
  async htmlToWord() {
    // Create an empty Word object:
    // const pptx = officegen('pptx');

    // Let's add a title slide:


    this.ctx.status = 200;
    this.ctx.body = {
      // data: docx,
      // out,
    };
  }
  // parse()
  async parse(req) {
    const form = new formidable.IncomingForm();
    return new Promise(resolve => {
      form.parse(req, (err, fields, files) => {
        resolve({ fields, files });
      });
    });
  }
  OptionsFile() {
    const { fileHash, fileName } = this.ctx.request.body;
    const ext = extractExt(fileName);
    const filePath = path.resolve(UPLOAD_DIR, `${fileHash}${ext}`);
    // 返回已经上传切片名
    const createUploadedList = async fileHash =>

      (fse.existsSync(path.resolve(UPLOAD_DIR, fileHash))
        ? await fse.readdir(path.resolve(UPLOAD_DIR, fileHash))
        : []);

    if (fse.existsSync(filePath)) {

      this.ctx.body = { data: '已上传', status: true };
      this.ctx.status = 200;
      this.ctx.res.end(
        JSON.stringify({
          shouldUpload: false,
        })
      );
    } else {
      this.ctx.body = { data: '已存在', status: true };
      this.ctx.status = 200;
      createUploadedList(fileHash);
      this.ctx.res.end(
        JSON.stringify({
          shouldUpload: true,
        })
      );

    }
  }
  async UploadFile() {
    // eslint-disable-next-line no-undef
    // const aaa = this.ctx.getFileStream();
    // console.log(UPLOAD_DIR, '***************', this.ctx.request.body.index);
    // const extraParams = await this.parse(this.ctx.req);
    // const stream = await this.ctx.getFileStream();
    // const { req, res } = this.ctx.req;
    const multipart = new multiparty.Form();
    multipart.encoding = 'utf-8';

    await new Promise(resolve => {
      multipart.parse(this.ctx.req, (err, fields, files) => {

        if (err) {

          this.ctx.status = 500;
          this.ctx.end('process file chunk failed');
          return;
        }
        const [ chunk ] = files.file;
        const [ hash ] = fields.fileHash;
        const [ fileHash ] = fields.fileHash;
        // const [ filename ] = fields.fileName;
        const filePath = path.resolve(
          UPLOAD_DIR,
          `${fileHash}`
        );
        const chunkDir = path.resolve(UPLOAD_DIR, fileHash);

        // 文件存在直接返回
        if (fse.existsSync(filePath)) {

          this.ctx.body = { data: '文件已存在', status: true };
          this.ctx.status = 304;
        } else {
          // 切片目录不存在，创建切片目录

          this.ctx.body = { data: '保存成功', status: true };
          this.ctx.status = 200;
          fse.mkdirs(chunkDir);
        }
        fse.move(chunk.path, path.resolve(chunkDir, hash));
        // this.ctx.end('received file chunk');
        resolve();
        // if (!fse.existsSync(chunkDir)) {

        // }s
        // fs-extra 专用方法，类似 fs.rename 并且跨平台
        // fs-extra 的 rename 方法 windows 平台会有权限问题
        // https://github.com/meteor/meteor/issues/7852#issuecomment-255767835
      });
    });
  }
  async Login() {
    console.log('this.ctx.request', this.ctx.request.body);

    const userName = this.ctx.request.body.userName;
    const password = this.ctx.request.body.password;
    const sql =
      " SELECT userName FROM admin_user WHERE userName = '" +
      userName +
      "' AND password = '" +
      password +
      "'";

    const res = await this.app.mysql.query(sql);

    if (res.length > 0) {
      // 登录成功,进行session缓存
      // 签发token
      console.log('rrrrrrr', res[0].userName);

      const token = JWT.sign({
        payload: res[0].userName,
      },
      res[0].userName
        // this.config.jwt.secret, {
        //   expiresIn: 60 * 60,
        // }
        // console.log('99999999999999', this.config)

      );
      // const openId = new Date().getTime();
      this.ctx.cookies.set('Auth Lbxin', token, {
        // domain: 'http://192.168.13.112:3000',
        // httpOnly: false,  //document.cookie 获取 cookie
        encrypt: true,
        maxAge: 1000 * 3600 * 24,
      });
      this.ctx.body = { data: '登录成功', token, status: true };
      this.ctx.status = 200;
    } else {
      this.ctx.body = { data: '登录失败', status: false };
      this.ctx.status = 401;
    }
  }
  async getArticleList() {

    const sql = 'SELECT article.id as id,' +
      'article.title as title,' +
      'article.article_content as article_content,' +
      'article.introduce as introduce,' +
      'article.articleImg as articleImg,' +
      'article.addTime as addTime,' +
      // "FROM_UNIXTIME(article.addTime,'%m-%d-%Y') as addTime,"+
      'article.view_count as view_count ,' +
      '.type.typeName as typeName ' +
      'FROM article LEFT JOIN type ON article.type_id = type.Id';

    const results = await this.app.mysql.query(sql);

    this.ctx.body = {
      data: results,
    };
  }

  async getShareTopicListById() {
    const id = this.ctx.params.id,
      sql = `SELECT * FROM topicList  WHERE topic_id=${id}`;
    const res = await this.app.mysql.query(sql);
    this.ctx.body = {
      data: res,
    };
  }

  async getShareTopicList() {
    const sql = 'SELECT * FROM shareTopic';
    const res = await this.app.mysql.query(sql);

    this.ctx.body = {
      data: res,
    };
  }
  async getShareItemById() {
    const id = this.ctx.params.id,
      sql = `SELECT * FROM topicList WHERE id=${id}`;
    const res = await this.app.mysql.query(sql);
    this.ctx.body = {
      data: res,
    };
  }
  async getArticleById() {
    const id = this.ctx.params.id;
    const sql = `SELECT * from article WHERE id=${id}`;
    const results = await this.app.mysql.query(sql);
    this.ctx.body = {
      data: results,
    };
  }
  async getMiQuanList() {

    const sql = 'SELECT * from miquan';

    const results = await this.app.mysql.query(sql);

    this.ctx.body = {
      data: results,
    };
  }
}

module.exports = HomeController;
